import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import * as authAPI from '../api/auth';
import { User } from '../types/user';
import type { AuthData } from '../api/auth';

// 路由常量
const AUTH_ROUTES = {
  LOGIN: '/auth/login',
  REGISTER: '/auth/register',
  VERIFY_EMAIL: '/auth/verify-email',
};

// 定义状态类型
interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
}

// 验证邮箱响应类型
interface VerifyEmailResponse {
  message: string;
  status: 'verified' | 'already_verified' | 'error';
}

// 初始状态
const initialState: AuthState = {
  user: (() => {
    const user = authAPI.getStoredUser();
    console.log('初始化用户状态:', user);
    return user;
  })(),
  isAuthenticated: (() => {
    const isAuth = authAPI.isAuthenticated();
    console.log('初始化认证状态:', isAuth);
    return isAuth;
  })(),
  isLoading: false,
  error: null,
};

// 异步action - 登录
export const login = createAsyncThunk<
  AuthData,
  { username: string; password: string },
  { rejectValue: string }
>('auth/login', async (credentials, { rejectWithValue }) => {
  try {
    const response = await authAPI.login(credentials);
    return response;
  } catch (error) {
    if (error instanceof Error) {
      return rejectWithValue(error.message);
    }
    return rejectWithValue('登录失败');
  }
});

// 异步action - 注册
export const register = createAsyncThunk<
  AuthData,
  { username: string; email: string; password: string },
  { rejectValue: string }
>('auth/register', async (userData, { rejectWithValue }) => {
  try {
    const response = await authAPI.register(userData);
    return response;
  } catch (error) {
    if (error instanceof Error) {
      return rejectWithValue(error.message);
    }
    return rejectWithValue('注册失败');
  }
});

// 验证邮箱
export const verifyEmail = createAsyncThunk<
  VerifyEmailResponse,
  string,
  { rejectValue: string }
>('auth/verifyEmail', async (token, { rejectWithValue }) => {
  try {
    const response = await authAPI.verifyEmail(token);
    return response as VerifyEmailResponse;
  } catch (error) {
    return rejectWithValue(error instanceof Error ? error.message : '邮箱验证失败');
  }
});

// 异步action - 获取当前用户信息
export const getCurrentUser = createAsyncThunk<
  User,
  void,
  { rejectValue: string }
>('auth/getCurrentUser', async (_, { rejectWithValue }) => {
  try {
    const user = await authAPI.getCurrentUser();
    return user;
  } catch (error) {
    if (error instanceof Error) {
      return rejectWithValue(error.message);
    }
    return rejectWithValue('获取用户信息失败');
  }
});

// 创建auth slice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout: (state) => {
      authAPI.clearAuthData();
      state.user = null;
      state.isAuthenticated = false;
      state.error = null;
      window.location.href = AUTH_ROUTES.LOGIN;
    },
    clearError: (state) => {
      state.error = null;
    }
  },
  extraReducers: (builder) => {
    // 登录
    builder
      .addCase(login.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isAuthenticated = true;
        state.user = action.payload.user;
        state.error = null;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '登录失败';
        authAPI.clearAuthData();
      });

    // 注册
    builder
      .addCase(register.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(register.fulfilled, (state, action) => {
        state.isLoading = false;
        state.error = null;
        // 注册成功后重定向到登录页面
        window.location.href = AUTH_ROUTES.LOGIN;
      })
      .addCase(register.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '注册失败';
      });

    // 验证邮箱
    builder
      .addCase(verifyEmail.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(verifyEmail.fulfilled, (state, action) => {
        state.isLoading = false;
        state.error = null;
      })
      .addCase(verifyEmail.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '邮箱验证失败';
      });

    // 获取当前用户
    builder
      .addCase(getCurrentUser.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getCurrentUser.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isAuthenticated = true;
        state.user = action.payload;
        state.error = null;
      })
      .addCase(getCurrentUser.rejected, (state, action) => {
        state.isLoading = false;
        state.isAuthenticated = false;
        state.user = null;
        state.error = action.payload || '获取用户信息失败';
      });
  },
});

// 导出action
export const { logout, clearError } = authSlice.actions;

export default authSlice.reducer; 